package com.jrfid.smartcabinet.demo.ui

import android.Manifest
import android.app.PendingIntent
import android.app.PendingIntent.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.nfc.NfcAdapter
import android.os.Bundle
import android.view.MenuItem
import androidx.activity.viewModels
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.blankj.utilcode.util.LogUtils
import com.jrfid.smartcabinet.demo.R
import com.jrfid.smartcabinet.demo.databinding.ActivityMainBinding
import android.hardware.usb.UsbManager

import android.content.IntentFilter
import android.content.pm.PackageManager
import com.jrfid.smartcabinet.demo.utils.UsbDevicesConst
import android.hardware.usb.UsbDevice
import android.util.Base64
import androidx.core.content.PermissionChecker
import com.blankj.utilcode.util.ToastUtils
import com.jrfid.devicemanager.library.CMDData
import com.jrfid.devicemanager.library.ConnectDevices
import com.jrfid.devicemanager.library.DeviceType
import com.jrfid.devicemanager.library.DevicesManager
import com.jrfid.devicemanager.library.connect.SerialPortConnectHandle
import com.jrfid.devicemanager.library.connect.TcpServerConnectHandle
import com.jrfid.smartcabinet.demo.arcface.FaceServer
import com.jrfid.smartcabinet.demo.ui.setting.SettingFragmentArgs
import com.jrfid.smartcabinet.demo.ui.setting.SettingFragmentDirections
import com.jrfid.smartcabinet.demo.utils.Config
import com.jrfid.smartcabinet.demo.utils.KTDataUtils
import com.mc.android.mcethernet.McEthernetConfig
import com.mc.enjoysdk.*
import com.mc.enjoysdk.result.McResultBool
import com.mc.enjoysdk.transform.McSecurePasswordState
import com.mc.enjoysdk.util.EnjoyUtil
import com.xgzx.veinmanager.VeinApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


const val ACTION_USB_PERMISSION = "com.jrfid.smartcabinet.demo.ui.USB_PERMISSION"

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var navController: NavController

    private val viewModel: MainViewModel by viewModels()
    private val scope = MainScope()

    init {
//        System.loadLibrary("ickinglib")
    }

    /**
     * 监听usb设备
     */
//    private val usbBroadcastReceiver = object : BroadcastReceiver() {
//        override fun onReceive(context: Context, intent: Intent) {
//            when (intent.action) {
//                UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
//
//                }
//                UsbManager.ACTION_USB_DEVICE_DETACHED -> {
//
//                }
//                ACTION_USB_PERMISSION -> {
//                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
//                        //同意权限
//                        val device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE) as UsbDevice?
//                        device?.let {
//                            connectNfcReader(it)
//                        }
//                    } else {
//                        LogUtils.d("拒绝usb权限")
//                    }
//                }
//            }
//        }
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        ActivityCompat.requestPermissions(
//            this,
//            arrayOf(
//                Manifest.permission.INTERNET,
//                Manifest.permission.ACCESS_WIFI_STATE,
//                Manifest.permission.ACCESS_NETWORK_STATE,
//                Manifest.permission.NFC,
//                Manifest.permission.CAMERA,
//                Manifest.permission.READ_PHONE_STATE,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.READ_EXTERNAL_STORAGE
//            ),
//            100
//        )
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        navController = (supportFragmentManager.findFragmentById(R.id.container) as NavHostFragment).navController
        binding.toolbar.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.main_menu_setting -> {
                    navController.navigate(R.id.settingFragment, SettingFragmentArgs(navController.currentDestination?.id != R.id.loginFragment).toBundle())
                }
            }
            return@setOnMenuItemClickListener true
        }
        viewModel.showSettingMenu.observe(this, Observer {
            binding.toolbar.menu.findItem(R.id.main_menu_setting).isVisible = it
        })
//        viewModel.readICCard.observe(this) {
//            readICCard(it)
//        }
//        val filter = IntentFilter()
//        filter.addAction(ACTION_USB_PERMISSION)
//        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
//        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
//        registerReceiver(usbBroadcastReceiver, filter)
//        connectUsbDevice()
        initDevice()
        initSerialPort()
        FaceServer.getInstance().init(this)
//        SerialPortManager.instance.openSerialPort()
    }

    private fun initDevice() {
        if (EnjoyUtil.isEnjoySupport()) {
            val secure = McSecure.getInstance(this)
            if (secure.checkSafeProgramOfSelf() == McResultBool.FALSE) {
                if (secure.securePasswdStatus == McSecurePasswordState.MC_SECURE_PASSWD_EMPTY) {
                    secure.setSecurePasswd("", "Ab88888888")
                }
                secure.registSafeProgram("Ab88888888")
            }
            val mcEthTether = McEthTether.getInstance(this)
            mcEthTether.enableEthTether(false, true)
            val mcEthernet = McEthernet.getInstance(this)
            if (mcEthernet.isEthernetEnable == McResultBool.TRUE) {
                mcEthernet.switchEthernet(true)
            }
            val config = mcEthernet.mcEthernetConfig
            if (!(config.mode == McEthernetConfig.STATIC_MODE && config.ipV4Address == "192.168.1.103")) {
                config.mode = McEthernetConfig.STATIC_MODE
                config.ipV4Address = "192.168.1.103"
                config.gateway = "192.168.1.1"
                config.subnetMask = "255.255.255.0"
                mcEthernet.setEthernetConfig(config)
            }
//            val mcHome = McHome.getInstance(this)
//            if (mcHome.homePackage != packageName) {
//                mcHome.homePackage = packageName
//            }
//            val mcKeepAlive = McKeepAlive.getInstance(this)
//            if (mcKeepAlive.isKeepAliveOpen == McResultBool.FALSE) {
//                mcKeepAlive.EnableKeepAlive(true)
//            }
//            if (mcKeepAlive.isKeepAliveApp(packageName) != McErrorCode.ENJOY_KEEP_ALIVE_MANAGER_IS_KEEP_ALIVE) {
//                mcKeepAlive.addKeepAliveAPP(arrayListOf(McKeepAliveApp().apply {
//                    this.packagename = packagename
//                    this.interval = 10 * 60
//                    this.priority = 999
//                }))
//            }
            McSystemUi.getInstance(this).let {
                it.temporarilySwitchNavigation(false)
                it.temporarilySwitchStatusBar(false)
                it.switchStatusBarAndNavigationOverwrite(false)
            }

        }
    }

    private fun initSerialPort() {
        DevicesManager.instance.addOnDeviceDataListener(object : DevicesManager.OnDeviceDataCallback {
            override fun onDataReceived(deviceType: DeviceType, address: Byte, byteArray: ByteArray) {
                LogUtils.d("Recv : ${deviceType} , ${address} , ${KTDataUtils.byteArrayToHex(byteArray)}")
            }

            override fun onDataSend(deviceType: DeviceType, address: Byte, byteArray: ByteArray) {
                LogUtils.d("Send : ${deviceType} , ${address} , ${KTDataUtils.byteArrayToHex(byteArray)}")
            }

        })
        scope.launch(Dispatchers.IO) {
//            val pairsMap = hashMapOf<Byte, String>()
//            Config.getCabinetList().forEachIndexed { index, model ->
//                pairsMap[(index + 1).toByte()] = model.address.get() ?: ""
//            }
            DevicesManager.instance.connectAllDevices(ConnectDevices().apply {
//                this.mainBoardConnectHandle = SerialPortConnectHandle("/dev/ttyS4", 115200)
                this.fingerVeinConnectHandle = SerialPortConnectHandle("/dev/ttyS3", 115200)
                this.mainBoardConnectHandle = TcpServerConnectHandle(
                    serverPort = 10000,
                    addressMap = hashMapOf(Pair(0x01, "192.168.1.7"), Pair(0x02, "192.168.1.8")),
                    readerProtocol = object : TcpServerConnectHandle.ReaderProtocol {
                        override fun getBodyLength(header: ByteArray): Int = header[1].toInt()

                        override fun getHeaderLength(): Int = 2

                    })
            })
            delay(5000)
            Config.getCabinetList().forEach {
                val address = (it.address.get() ?: "1").toInt().toByte()
                DevicesManager.instance.startSyncDataMode(DeviceType.UHF, address)
                var data = DevicesManager.instance.sendDataSync(deviceType = DeviceType.UHF, address = address, byteArray = CMDData.R2000.getDevicePower(), timeout = 5000)
                if (data != null && data.size >= 11) {
                    LogUtils.d("当前功率：0x${KTDataUtils.byteToHex(data[8])}")
                    if (data[8] != 33.toByte()) {
                        //设置功率
                        data = DevicesManager.instance.sendDataSync(DeviceType.UHF, address, CMDData.R2000.setDevicePower(33), 1000)
                        if (data != null && data.size >= 11 && data[8] == 0x10.toByte()) {
                            LogUtils.d("功率设置成功")
                        }
                    }
                }
                data = DevicesManager.instance.sendDataSync(DeviceType.UHF, address, CMDData.R2000.getFrequencyRegion(), 5000)
                if (data != null && data.size >= 13) {
                    LogUtils.d("当前工作区域：${KTDataUtils.byteToHex(data[8])},频点：${KTDataUtils.byteToHex(data[9])} - ${KTDataUtils.byteToHex(data[10])}")
                    if (data[8] != (0x01).toByte() || data[9] != 0x07.toByte() || data[10] != 0x3B.toByte()) {
                        //设置频率
                        data = DevicesManager.instance.sendDataSync(DeviceType.UHF, address, CMDData.R2000.setFrequencyRegion(1), 1000)
                        if (data != null && data.size >= 13 && data[8] == 0x10.toByte()) {
                            LogUtils.d("工作区域设置成功")
                        }
                    }
                }
                data = DevicesManager.instance.sendDataSync(DeviceType.UHF, address, CMDData.R2000.getDeviceWorkAntenna(), 5000)
                if (data != null && data.size >= 11) {
                    LogUtils.d("${address}当前工作天线：${KTDataUtils.byteToHex(data[8])}")
                    if (data[8] != (0x00).toByte()) {
                        //设置工作天线
                        data = DevicesManager.instance.sendDataSync(DeviceType.UHF, address, CMDData.R2000.setDeviceWorkAntenna(0), 5000)
                        if (data != null && data.size >= 11 && data[8] == 0x10.toByte()) {
                            LogUtils.d("${address}工作天线设置成功")
                        }
                    }
                }
                DevicesManager.instance.stopSyncDataMode(DeviceType.UHF, address)
            }
        }
//        val text = "ABAbAbAb121212112".toByteArray()
//        LogUtils.d("${text}")
//        LogUtils.d("${Base64.encodeToString(text, Base64.NO_WRAP)}")
//        LogUtils.d("${Base64.encodeToString(text, Base64.DEFAULT)}")
//        LogUtils.d("${Base64.encodeToString(text, Base64.CRLF)}")
//        LogUtils.d("${Base64.encodeToString(text, Base64.NO_CLOSE)}")
//        LogUtils.d("${Base64.encodeToString(text, Base64.NO_PADDING)}")
//        LogUtils.d("${Base64.encodeToString(text, Base64.URL_SAFE)}")
//        LogUtils.d("${VeinApi.FVEncodeBase64(text, text.size.toLong())}")
    }

    override fun onDestroy() {
        FaceServer.getInstance().unInit()
        DevicesManager.instance.disconnectAllDevices()
//        MainBoardManager.instance.close()
//        SerialPortManager.instance.closeSerialPort()
        super.onDestroy()
    }

//    private fun connectUsbDevice() {
//        val usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
//        val deviceList = usbManager.deviceList
//        if (deviceList.isNullOrEmpty()) {
//            LogUtils.d("未连接usb设备")
//            return
//        }
//        val deviceIterator = deviceList.values.iterator()
//        while (deviceIterator.hasNext()) {
//            val it = deviceIterator.next()
//            if (it.vendorId == UsbDevicesConst.NfcReader.VENDOR_ID && it.productId == UsbDevicesConst.NfcReader.PRODUCT_ID) {
//                //nfc读卡器
//                if (usbManager.hasPermission(it)) {
//                    connectNfcReader(it)
//                } else {
//                    val intent = getBroadcast(this, 100, Intent(ACTION_USB_PERMISSION), FLAG_UPDATE_CURRENT)
//                    usbManager.requestPermission(it, intent)
//                }
//            }
//        }
//    }

//    private val nfcReaderUsbDeviceMap = hashMapOf<String, UsbDevice>()
//    private var nfcReader: ReaderJni? = null
//
//    private fun connectNfcReader(usbDevice: UsbDevice) {
//        val usbManager = getSystemService(Context.USB_SERVICE) as UsbManager
//        nfcReader = ReaderJni(usbManager)
//        val result = nfcReader?.rf_init(usbManager, 0, 0)
//        if (result == 0) {
//            LogUtils.d("设备连接成功")
//            nfcReaderUsbDeviceMap[usbDevice.deviceName] = usbDevice
//        }
//    }
//
//    private fun readICCard(name: String) {
//        val usbDevice = nfcReaderUsbDeviceMap[name]
//        nfcReader?.openReader(usbDevice)
//        val data = ByteArray(10)
//        val r = nfcReader?.rf_ICCard(0, 0, data)
//        if (0.toShort() == r) {
//            //获取卡号成功
//            val hex = KTDataUtils.byteArrayToHex(data)
//            LogUtils.d("IC卡号十六进制：${hex}")
//            viewModel.currentICCardNo.postValue(hex)
//        } else {
//            LogUtils.d("IC卡号获取失败")
//            viewModel.currentICCardNo.postValue(null)
//        }
//    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        for (grant in grantResults) {
            if (grant == PackageManager.PERMISSION_DENIED) {
                ToastUtils.showShort(getString(R.string.text_permissions_denied))
                return
            }
        }
    }

    override fun onBackPressed() {
        if (navController.backQueue.size > 2) {
            super.onBackPressed()
        }
    }
}